#include <iostream>
#include <string>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define CONV(addr_ptr) ((sockaddr*)addr_ptr)
#define Retey_Count 5 //断线重连

bool VisitServer(std::string& serverip, uint16_t serverport, int& cnt)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        //cout
        return false;
    }

    sockaddr_in server;
    server.sin_family = AF_INET;
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    server.sin_port = htons(serverport);

    //用connnet发起连接，且会自动bind
    int n = connect(sockfd, CONV(&server), sizeof server);
    if(n < 0)
    {
        //cout
        close(sockfd);
        return false;
    }

    cnt = 1;

    std::string buffer;
    std::cout << "please select func# ";
    std::getline(std::cin, buffer);
    write(sockfd, buffer.c_str(), buffer.size());

    // while(true)
    // {
        std::cout << "please enter# ";
        std::getline(std::cin, buffer);

        n = write(sockfd, buffer.c_str(), buffer.size());
        if(n > 0)
        {
            char backbuffer[1024];
            int m = read(sockfd, backbuffer, sizeof backbuffer - 1);
            if(m > 0)
            {
                backbuffer[m] = 0;
                std::cout << backbuffer << std::endl;
            }
            else if(m == 0) //读完
            {
                // break;
            }
            else            //读错 
            {
                close(sockfd);
                return false;
            }
        }
        else
        {
            close(sockfd);
            // return false;
        }
    // }
    close(sockfd);
    return true;
}

int main(int argc, char* argv[])
{
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);


    //断线重连
    int cnt = 1;
    while(cnt <= Retey_Count)
    {
        bool result = VisitServer(serverip, serverport, cnt);
        if(result) break;
        else
        {
            std::cout << "server offline... retrying: count: " << cnt++ << std::endl;
            sleep(1);
        }
    }
    if(cnt == Retey_Count + 1)
        std::cout << "server offline..." << std::endl;
}